package com.itcoon.cloud.framework.ex.register;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.helpers.MessageFormatter;

import java.util.HashMap;
import java.util.Map;

public class DefaultErrorCodeRegister implements IErrorCodeRegister {

    private static final Logger log = LoggerFactory.getLogger(DefaultErrorCodeRegister.class);

    private static final Map<String, Map<String, String>> ERROR_CODE_CACHE_MAP = new HashMap<>();


    @Override
    public void preRegister() {
        ERROR_CODE_CACHE_MAP.clear();
        log.info("=================================Error code start registering=================================");
    }

    @Override
    public void register(String applicationName, String errorCode, String message) {
        log.info("Error code registered: [{}] - {}", errorCode, message);
        Map<String, String> errorCodeMap = ERROR_CODE_CACHE_MAP.computeIfAbsent(applicationName, k -> new HashMap<>());
        if(errorCodeMap.get(errorCode) != null){
            log.warn("Duplicate Error code: [{}], it will be overwritten", errorCode);
        }
        errorCodeMap.put(errorCode, message);
    }

    @Override
    public void postRegister() {
        log.info("=================================All of error code registered=================================");
    }

    @Override
    public String getMessage(String applicationName, String code, String... args) {
        return MessageFormatter.arrayFormat(ERROR_CODE_CACHE_MAP.get(applicationName).get(code), args).getMessage();
    }
}
